package P075_SynchronizeCompareToAndEquals;

import org.apache.commons.lang3.builder.CompareToBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @ClassName : SynchronizeCompareToAndEquals
 * @Description :集合中的元素必须做到compareTo和equals同步  equals是判断元素是否相等，compareTo是判断元素在排序中的位置是否相同
 * @Author : wukj1
 * @Date: 2022/4/2
 **/
public class SynchronizeCompareToAndEquals {

    @Test
    public void test(){
        List<City> cities = new ArrayList<>();
        cities.add(new City("21","上海"));
        cities.add(new City("21","沪"));
        //排序
        Collections.sort(cities);
        //查找对象
        City city = new City("21", "沪");
        //indexOf方法获取索引值
        int i = cities.indexOf(city);
        System.out.println("indexOf获取的索引值：" + i);
        //binarySearch查找索引值
        int i1 = Collections.binarySearch(cities, city);
        System.out.println("binarySearch获取的索引值：" + i1);
    }

}

class City implements Comparable<City>{
    //城市编码
    private String code;
    //城市名称
    private String name;

    public City(String code, String name) {
        this.code = code;
        this.name = name;
    }

    @Override
    public int compareTo(City o) {
        //按照城市名称进行排序
        return new CompareToBuilder()
                .append(name,o.name)
                .toComparison();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        City city = (City) o;
        //按照城市编码进行排序
//        return new EqualsBuilder()
//                .append(code,city.code)
//                .isEquals();
        return new EqualsBuilder()
                .append(name,city.name)
                .isEquals();
    }

}
